//
// Created by 62763 on 2020/10/22.
//

#ifndef L_SQLIST_SQLIST_H
#define L_SQLIST_SQLIST_H

#include<cstdio>
#include<cstdlib>
#include<iostream>

#define MaxSize 100
#define OK true
#define Status int
using namespace std;
typedef int ElemType;
typedef struct SqList {
    ElemType *elem;
    int length;
    int listsize;
};

Status InitList_Sq(SqList &L);

Status CompareElem(ElemType a, ElemType b);

Status LocateElem_Sq(SqList &L, ElemType e);

Status ListInsert_Sq(SqList &L, int pos, ElemType e);

Status ListExtend_Sq(SqList &L);

Status ListDelete_Sq(SqList &L, int pos, ElemType *e);

Status InitList_Sq(SqList &L) {
    L.elem = (ElemType *) malloc(MaxSize * sizeof(ElemType));
    if (!L.elem) {
        return false;
    }
    L.length = 0;
    L.listsize = MaxSize;
    return true;
}

Status CompareElem(ElemType a, ElemType b) {
    return a == b;
}

Status LocateElem_Sq(SqList &L, ElemType e) {
    int i = 0;
    while (i < L.length && !CompareElem(L.elem[i], e)) i++;
    return i < L.length ? i + 1 : 0;
}

Status ListInsert_Sq(SqList &L, int pos, ElemType e) { //将元素e插入pos位置
    if (pos < 1 || pos > L.length + 1) return false;
    if (L.length >= L.listsize) if (!ListExtend_Sq(L)) return false;//线性表拓展失败
    int i = L.length;
    while (i >= pos) {
        L.elem[i] = L.elem[i - 1];//后移
        i--;
    }
    L.elem[pos - 1] = e;
    L.length++;
    return true;
}

Status ListExtend_Sq(SqList &L) {//线性表分配空间不足  拓展空间
    ElemType *newbase = (ElemType *) realloc(L.elem, (L.listsize + 10) * sizeof(ElemType));
    if (!newbase) return false;
    L.elem = newbase;
    L.listsize += 10;
    return true;
}

Status ListDelete_Sq(SqList &L, int pos) {//根据索引删除线性表中元素
    if (pos < 1 || pos > L.length) return false;//表中数据不存在  报错
    int i = pos - 1;
    while (i < L.length - 1) {
        L.elem[i] = L.elem[i + 1];
        i++;
    }
    L.length--;
    return true;
}

Status ListUnion_Sq(SqList &A, SqList B) {
    int len_A = A.length, len_B = B.length;
    for (int i = 0; i < len_B; i++) {
        if (!LocateElem_Sq(A, B.elem[i])) {
            ListInsert_Sq(A, ++len_A, B.elem[i]);
        }
    }
}


#endif //L_SQLIST_SQLIST_H
